//
//  TaskAlertViewController.m
//  HAODE
//
//  Created by LiYinDi on 15/12/30.
//  Copyright © 2015年 reabam.com. All rights reserved.
//

#import "TaskAlertViewController.h"
#import "TaskAlertTableViewCell.h"
#import "RDVTabBarController.h"
#import "HttpRequest.h"
#import "EGORefreshTableHeaderView.h"
#import "OrderDetailViewController.h"
#import "OrderDeliveryDetailViewController.h"
#import "CheckVouchDetailViewController.h"
#import "WhsOutAddWhsInDetailViewController.h"
#import "BookingOrderDetailViewController.h"
#import "GoodsInOrderDetailViewController.h"
#import "AllotOrderDetailViewController.h"
#import "NeedOrderDetailViewController.h"
@interface TaskAlertViewController ()<EGORefreshTableHeaderDelegate>
{
    NSUInteger _PageIndex;
    NSUInteger _TotalCount;
    NSUInteger _TotalPage;
    NSMutableArray *modelArray;
    EGORefreshTableHeaderView *_refreshHeaderView;
    BOOL _reloading;
    UIView*noDataView;

}

@end

@implementation TaskAlertViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    modelArray=[NSMutableArray array];
    if (_refreshHeaderView == nil) {
        EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - _listTableView.bounds.size.height, self.view.frame.size.width, _listTableView.bounds.size.height)];
        view.delegate = self;
        [_listTableView addSubview:view];
        _refreshHeaderView = view;
    
    }
    
    //  update the last update date
   
    [self setNavigation];
    [self setAutoLayout];
     [_refreshHeaderView refreshLastUpdatedDate];
    _PageIndex=0;
    [self loadMessageListNextPage:_PageIndex];
    
   }
-(void) loadMessageListNextPage:(NSUInteger)oldPageNum {
    if(oldPageNum!=0 && _TotalCount<=modelArray.count)
        return;
    if(oldPageNum == 0){
        [modelArray removeAllObjects];
        [_listTableView reloadData];
    }
    _PageIndex=oldPageNum+1;
    [self requestServiceList: _PageIndex pageSize:20];
}
-(void)requestServiceList:(NSUInteger)pageIndex pageSize:(NSUInteger)pageSize
{
    
    [noDataView removeFromSuperview];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"tokenId"];
    NSNumber *pageSizeNumber = [NSNumber numberWithInteger:pageSize];
    NSNumber *pageIndexNumber = [NSNumber numberWithInteger:pageIndex];
    [params setObject:pageSizeNumber forKey:@"PageSize"];
    [params setObject:pageIndexNumber forKey:@"PageIndex"];
    [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
    
    [HttpRequest requestData:@"MsgCenter/TaskRemind/List" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                NSLog(@"data====%@",severDataDict.dataDict);
                [Global hideProgressHUDInternal:self.view];
                _TotalCount=[[severDataDict.dataDict objectForKey:@"TotalCount"] integerValue];
                
                if (_TotalCount%20!=0) {
                    _TotalPage=_TotalCount/20+1;
                }
                else if (_TotalCount%20==0)
                {
                    _TotalPage=_TotalCount/20;
                }
                NSMutableArray *mArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                if (mArray.count>0)
                {}else{
                    noDataView=[[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight/2-50, ScreenWidth, 80)];
                    [self.view addSubview:noDataView];
                    UIImageView*noImage=[[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth/2-47, 0, 94, 51)];
                    noImage.image=[UIImage imageNamed:@"meiyoushuju"];
                    [noDataView addSubview:noImage];
                    UILabel*noLabel=[[UILabel alloc]initWithFrame:CGRectMake(0,65, ScreenWidth, 14)];
                    noLabel.text=@"没有列表数据，赶紧去添加！";
                    noLabel.textColor=zhonghuiColor; noLabel.font=[UIFont systemFontOfSize:14];
                    noLabel.textAlignment=NSTextAlignmentCenter;
                    [noDataView addSubview:noLabel];

                }
                for (NSDictionary* dicc in mArray )
                {
                    TaskAlertModel *model = nil;
                    model=[TaskAlertModel mj_objectWithKeyValues:dicc];
                    if(model != nil)
                        [modelArray addObject:model];
                }
                
                [_listTableView reloadData];
                [self  doneLoadingTableViewData];
            }else{
                [Global hideProgressHUDInternal:self.view];
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return modelArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 110;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * const  ServiceManagementIdentifier = @"SystemNotificatioanIdentifier";
    TaskAlertTableViewCell *cell=( TaskAlertTableViewCell *)[tableView dequeueReusableCellWithIdentifier: ServiceManagementIdentifier];
    if (cell==nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"TaskAlertTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model=  modelArray[indexPath.row];
    
       if (indexPath.row == [modelArray count] - 1)
    {
        if (_PageIndex<=_TotalPage) {
            //  NSLog(@"###LOADING???");
            [self loadMessageListNextPage:_PageIndex];
        }
    }
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TaskAlertModel *model=modelArray[indexPath.row];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:model.trId forKey:@"trId"];
    
    [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
    
    [HttpRequest requestData:@"MsgCenter/TaskRemind/Read" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
     
                
                [modelArray removeAllObjects];
                _PageIndex=0;
                [self loadMessageListNextPage:_PageIndex];
                
                if ([model.taskType isEqualToString:@"DOrder_NA"]||[model.taskType isEqualToString:@"DOrder_ND"]) {
                    OrderDetailViewController *detailViewController = [[OrderDetailViewController alloc] init];
                    detailViewController.orderId=model.orderId;
                    
                    [self.navigationController pushViewController:detailViewController animated:YES];

                }else if ([model.taskType isEqualToString:@"DBookingOrder_NA"]) {
                    BookingOrderDetailViewController *detailViewController = [[BookingOrderDetailViewController alloc] init];
                    detailViewController.orderId=model.orderId;
                    [self.navigationController pushViewController:detailViewController animated:YES];

                    
                }else if ([model.taskType isEqualToString:@"DNeedOrder_Results"]) {
                    NeedOrderDetailViewController *detailViewController = [[NeedOrderDetailViewController alloc] init];
                    detailViewController.orderId=model.orderId;
                    
                    [self.navigationController pushViewController:detailViewController animated:YES];

                    
                }else if ([model.taskType isEqualToString:@"DAllotOrder_NA"]||[model.taskType isEqualToString:@"DAllotOrder_YO"]||[model.taskType isEqualToString:@"DAllotOrder_Results"]) {
                    AllotOrderDetailViewController *detailViewController = [[AllotOrderDetailViewController alloc] init];
                    detailViewController.orderId=model.orderId;
                    
                    [self.navigationController pushViewController:detailViewController animated:YES];
                }else if ([model.taskType isEqualToString:@"DGoodsInOrder_YO"]) {
                    GoodsInOrderDetailViewController *detailViewController = [[GoodsInOrderDetailViewController alloc] init];
                    detailViewController.orderId=model.orderId;
                    
                    [self.navigationController pushViewController:detailViewController animated:YES];

                    
                }else if ([model.taskType isEqualToString:@"DCheckVouch_NP"]) {
                    CheckVouchDetailViewController *detailViewController = [[CheckVouchDetailViewController alloc] init];
                    detailViewController.orderId=model.orderId;
                    
                    [self.navigationController pushViewController:detailViewController animated:YES];

                    
                }

                
                
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];

}
#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
    [modelArray removeAllObjects];
    _PageIndex=0;
    [self loadMessageListNextPage:_PageIndex];
    //  should be calling your tableviews data source model to reload
    //  put here just for demo
    _reloading = YES;
    
}

- (void)doneLoadingTableViewData{
    
    //  model should call this when its done loading
    _reloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:_listTableView];
    
}


#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}

-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    
    [self reloadTableViewDataSource];
    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:3.0];
    
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
    
    return _reloading; // should return if data source model is reloading
    
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
    
    return [NSDate date]; // should return date data source was last changed
    
}

-(void)setNavigation
{
    [[self rdv_tabBarController] setTabBarHidden:YES];
    
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    UILabel* titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0,40, 23)];
    titleLabel.text=@"任务通知";
    titleLabel.font=[UIFont systemFontOfSize: 17];
    self.navigationItem.titleView=titleLabel;
 
}
-(void)BackAction:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)setAutoLayout
{
    [_listTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.top.equalTo(self.view.mas_top).with.offset(64) ;
        make.bottom.equalTo(self.view.mas_bottom);
        
    }];

   

    
}

@end
